#include <iostream>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <unistd.h>
#include <sstream>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace MutexModule;
    const std::string gsep = "\n\r";

    class LogStrategy
    {
    public:
        ~LogStrategy() = default;
        virtual void SyncLog(const std::string& message) = 0;
    };

    class ConsoleLogStrategy: public LogStrategy
    {
    public:
        ConsoleLogStrategy()
        {}

        void SyncLog(const std::string& message) override
        {
            LockGuard lockguard(_mutex);
            std::cout << message << gsep;
        }

    private:
        Mutex _mutex;
    };


    const std::string defaultpath = "./log/";
    const std::string defaultfile = "/My.log";

    class FileLogStrategy: public LogStrategy
    {
    public: 
        FileLogStrategy(const std::string& path = defaultpath, const std::string& file = defaultfile)
            :_path(path), _name(file)
        {
            LockGuard lockguard(_mutex);
            if(std::filesystem::exists(_path))
                return;
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch(std::filesystem::filesystem_error& e)
            {
                std::cerr << e.what() << std::endl;
            }
        }
        
        void SyncLog(const std::string& message) override
        {
            std::string filename = _path + (_path.back() == '/' ? "":"/") + _name;
            LockGuard lockguard(_mutex);
            std::ofstream out(filename, std::ios::app);
            out << message << gsep;
        }   

    private:
        std::string _path;
        std::string _name;
        Mutex _mutex;
    };

    enum class Level
    {
        DEBUG,
        FATAL,
        ERROR,
        INFO,
        WARNING
    };

    std::string Level2Str(Level level)
    {
        switch(level)
        {
            case Level::DEBUG:
                return "DEBUG";
            case Level::ERROR:
                return "ERROR";
            case Level::WARNING:
                return "WARNING";
            case Level::FATAL:
                return "FATAL";
            case Level::INFO:
                return "INFO";
            default:
                return "UNKNOWN";
        }
    }

    std::string GetTimeStamp()
    {
        time_t curr = time(nullptr);
        struct tm curr_t;
        localtime_r(&curr, &curr_t);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer), "%04d-%02d-%02d %02d:%02d:%02d", 
            curr_t.tm_year + 1900,
            curr_t.tm_mon + 11,
            curr_t.tm_mday,
            curr_t.tm_hour,
            curr_t.tm_min,
            curr_t.tm_sec           
        );

        return timebuffer;
    }

    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }    
        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
    
        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }
        class LogMessage
        {
        public:
            LogMessage(Level level, const std::string& name, int line_number, Logger& logger)
                :_level(Level2Str(level))
                ,_src_name(name)
                ,_line(line_number)
                ,_pid(getpid())
                ,_curr_time(GetTimeStamp())
                ,_logger(logger)
            {
                std::stringstream ss;
                ss 
                << "[" << _curr_time << "]" 
                << "[" << _level << "]" 
                << "[" << _pid << "]" 
                << "[" << _src_name << "]"
                << "[" << line_number << "]"
                << "-";

                _loginfo = ss.str();
            }

            template <typename T>
            LogMessage& operator<<(const T& info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if(_logger._fflush_strategy)
                    _logger._fflush_strategy->SyncLog(_loginfo);
            }

        private:
            int _line;
            pid_t _pid;
            std::string _level;
            std::string _src_name;
            std::string _curr_time;
            std::string _loginfo;
            Logger& _logger;
        };

        LogMessage operator()(Level level, const std::string& name, int line)
        {
            return LogMessage(level, name, line, *this);
        }

        ~Logger()
        {

        }

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    Logger logger;

    #define LOG(level) logger(level, __FILE__, __LINE__)
    #define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()

}